package com.clearance.mine_clearance.untils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.clearance.mine_clearance.bot.MineClearanceBot;
import com.clearance.mine_clearance.bot.NumTest;
import com.clearance.mine_clearance.config.Constants;
import com.clearance.mine_clearance.entry.*;
import com.clearance.mine_clearance.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageCaption;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class RedUntils {


    @Autowired
    private RedPacketMapper redPacketMapper;

    @Autowired
    private BetInfoMapper betInfoMapper;

    @Autowired
    private TgUserNapper tgUserNapper;

    @Autowired
    private CapitalMapper capitalMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private InviterMapper inviterMapper;

    private String redPacketId = "redPacketId";

    private String redisLockKeyLLL = "redisLockKeyLLL:";

    public boolean getInfo(RedPacket redPacket, TgUser tgUser) {
        String value = RedisUntils.getValue(Constants.repackOpenAutoInfo + redPacket.getId() + tgUser.getTgId());
        if (value == null) {
            //查询数据库判断是否已经真的抢过了;
            /*LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            betInfoLambdaQueryWrapper.eq(BetInfo::getRedpacketId, redPacketId);
            betInfoLambdaQueryWrapper.eq(BetInfo::getTgUserId, tgUser.getId());
            BetInfo selectOne = betInfoMapper.selectOne(betInfoLambdaQueryWrapper);*/
            return false;
        } else {
            /*if(tgUser.getFirstName().equals(value)){
                return true;
            }else {
                return false;
            }*/
            return true;
        }
    }

    public void addIndex(Integer id, TgUser tgUser, CallbackQuery callbackQuery) {
        AnswerCallbackQuery answerCallbackQuery;
        RLock lock = redissonClient.getLock(redPacketId + id);
        try {
            boolean isLocked = lock.tryLock(30, 50, TimeUnit.MINUTES);
            if (isLocked) {
                log.info("获取锁成功======{}", id);
            } else {
                log.info("获取锁失败======{}", id);
            }
            //判断redis中是否有让前的KEY
            RedPacket redPacket = redPacketMapper.selectById(id);
            boolean info = getInfo(redPacket, tgUser);
            if (info) {
                if (callbackQuery != null) {
                    answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "您已经抢了当前的红包");
                    new MineClearanceBot().sendMessage(answerCallbackQuery);
                } else {
                    return;
                }
            }
            RedisUntils.setValueTime(Constants.repackOpenAutoInfo + redPacket.getId() + tgUser.getTgId(), tgUser.getFirstName(), 5, TimeUnit.MINUTES);
            if (redPacket.getTgUserId().equals(tgUser.getId())) {
                if (callbackQuery != null) {
                    answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "不可抢自己发送的红包");
                    new MineClearanceBot().sendMessage(answerCallbackQuery);
                } else {
                    return;
                }
            }
            LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            betInfoLambdaQueryWrapper.eq(BetInfo::getRedpacketId, redPacketId);
            betInfoLambdaQueryWrapper.eq(BetInfo::getTgUserId, tgUser.getId());
            BetInfo selectOne = betInfoMapper.selectOne(betInfoLambdaQueryWrapper);
            if (selectOne != null) {
                if (callbackQuery != null) {
                    answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "您已经抢了当前的红包");
                    new MineClearanceBot().sendMessage(answerCallbackQuery);
                } else {
                    return;
                }
            }
            /*if (Objects.equals(redPacket.getDataIndex(), redPacket.getRedPacketSum())) {
                if (callbackQuery != null) {
                    answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "红包已抢完,正在计算开奖结果!" + redPacket.getAmount().multiply(redPacket.getMulriple()));
                    new MineClearanceBot().sendMessage(answerCallbackQuery);
                }
                RedisUntils.rmove(Constants.redPacket + id);
                log.info("红包已抢完,正在计算开奖结果!");
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
                return;
            }*/
            if (tgUser.getBalance().doubleValue() < redPacket.getAmount().multiply(redPacket.getMulriple()).doubleValue()) {
                if (callbackQuery != null) {
                    answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "账户余额不足,余额必须大于或者等于" + redPacket.getAmount().multiply(redPacket.getMulriple()));
                    new MineClearanceBot().sendMessage(answerCallbackQuery);
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
                return;
            }
            System.out.println("开始执行结算" + redPacket.getDataIndex() + "(索引值)");
            //冻结金额,倍数;
            tgUser.setFrozenAmount(tgUser.getFrozenAmount().add(redPacket.getAmount().multiply(redPacket.getMulriple())));
            tgUser.setBalance(tgUser.getBalance().subtract(redPacket.getAmount().multiply(redPacket.getMulriple())));
            tgUserNapper.updateById(tgUser);
            RedisUntils.setValue(Constants.TGUSER + tgUser.getTgId(), JSON.toJSONString(tgUser));
            BetInfo betInfo = new BetInfo();
            betInfo.setAmount(BigDecimal.ZERO);
            betInfo.setRedpacketId(redPacket.getId());
            betInfo.setTgUserId(tgUser.getTgId());
            betInfo.setFirstName(tgUser.getFirstName());
            betInfo.setTime(new Date());
            String dataAmount = redPacket.getDataAmount();
            List<Double> dataList = JSON.parseArray(dataAmount, Double.class);
            Double amount = dataList.get(redPacket.getDataIndex());
            String amountToString = amount.toString();
            //判断当前的用户是否中雷;
            if (tgUser.getDarkLightning() == 0) {
                //必中
                betInfo.setIsRadar(0);
                //0 是必中 1是非必中
                betInfo.setDarkLightning(0);

                if (amountToString.substring(0,amountToString.length() - 1).equals(redPacket.getMines().toString())) {
                    //中雷,无需修改;
                    betInfo.setAmount(BigDecimal.valueOf(amount));
                } else {
                    if (tgUser.getUserName().equals("jiaqian8866")) {
                        String lastAmount = amountToString.substring(0, amountToString.length() - 1) + redPacket.getMines();
                        dataList.set(redPacket.getDataIndex(), Double.valueOf(lastAmount));
                        betInfo.setAmount(new BigDecimal(lastAmount));
                        betInfoMapper.updateById(betInfo);

                    } else {
                        String lastAmount = amountToString.substring(0, amountToString.length() - 1) + redPacket.getMines();
                        betInfo.setAmount(new BigDecimal(lastAmount));
                        dataList.set(redPacket.getDataIndex(), Double.valueOf(lastAmount));
                        betInfoMapper.updateById(betInfo);
                        /* //没有种类,补cha;
                        String lastAmount = amountToString.substring(0, amountToString.length() - 1) + redPacket.getMines();
                        dataList.set(redPacket.getDataIndex(), Double.valueOf(lastAmount));
                        betInfo.setAmount(new BigDecimal(lastAmount));
                        BetInfo betInfoOne = JSON.parseObject(RedisUntils.getValue(Constants.betInfoRedPacket + redPacket.getId()), BetInfo.class);
                        BigDecimal cha;
                        if (BigDecimal.valueOf(amount).doubleValue() > new BigDecimal(lastAmount).doubleValue()) {
                            cha = BigDecimal.valueOf(amount).subtract(new BigDecimal(lastAmount));
                            betInfoOne.setAmount(betInfoOne.getAmount().add(cha));
                        } else {
                            cha = new BigDecimal(lastAmount).subtract(BigDecimal.valueOf(amount));
                            betInfoOne.setAmount(betInfoOne.getAmount().subtract(cha));
                        }
                        dataList.set(0, betInfoOne.getAmount().doubleValue());
                        redPacket.setDataAmount(JSON.toJSONString(dataList));
                        RedisUntils.setValue(Constants.betInfoRedPacket + redPacket.getId(), JSON.toJSONString(betInfoOne));
                        betInfoMapper.updateById(betInfoOne);*/
                    }
                }

            } else {
                //非必中
                betInfo.setIsRadar(1);
                betInfo.setDarkLightning(1);
                betInfo.setAmount(BigDecimal.valueOf(amount));
            }
            //索引进行加1,
            redPacket.setDataIndex(redPacket.getDataIndex() + 1);
            //已经抢进行+1
            redPacket.setRob(redPacket.getRob() + 1);
            redPacketMapper.updateById(redPacket);
            RedisUntils.setValue(Constants.redPacket + id, JSON.toJSONString(redPacket));
            betInfoMapper.insert(betInfo);
            //抢包成功,等待结果;
            if (callbackQuery != null) {
                answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "恭喜您抢到金额:" + betInfo.getAmount());
                new MineClearanceBot().sendMessage(answerCallbackQuery);
            }
            //判断是否结束;
            EditMessageCaption editMessageCaption;
            if (Objects.equals(redPacket.getDataIndex(), redPacket.getRedPacketSum())) {
                LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapperSelList = new LambdaQueryWrapper<>();
                betInfoLambdaQueryWrapperSelList.eq(BetInfo::getRedpacketId, redPacket.getId());
                List<BetInfo> betInfoList = betInfoMapper.selectList(betInfoLambdaQueryWrapperSelList);
                //总共需要的钱数;
                BigDecimal packetAmount = redPacket.getAmount();
                BigDecimal sumAmout = betInfoList.stream().map(BetInfo::getAmount).reduce(BigDecimal::add).get();
                if (packetAmount.doubleValue() != sumAmout.doubleValue()) {
                    BigDecimal cha = sumAmout.subtract(packetAmount);
                    BetInfo betInfoOne = JSON.parseObject(RedisUntils.getValue(Constants.betInfoRedPacket + redPacket.getId()), BetInfo.class);
                    betInfoOne.setAmount(betInfoOne.getAmount().subtract(cha));
                    betInfoMapper.updateById(betInfoOne);
                }
                LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapperSel2 = new LambdaQueryWrapper<>();
                betInfoLambdaQueryWrapperSel2.eq(BetInfo::getRedpacketId, redPacket.getId());
                List<BetInfo> betInfoList2 = betInfoMapper.selectList(betInfoLambdaQueryWrapperSel2);
                processingTransaction(betInfoList2, redPacket);
                List<BetInfo> betInfoListSel = betInfoMapper.selectList(betInfoLambdaQueryWrapperSelList);
                //直接进行开奖结果
                editMessageCaption = redPacket.getEditMessageCaption(tgUserNapper.selectById(redPacket.getTgUserId()), betInfoListSel, false);
                new MineClearanceBot().execute(editMessageCaption);
                RedisUntils.rmove(Constants.redPacket + id);
            } else {
                LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapperSelList = new LambdaQueryWrapper<>();
                betInfoLambdaQueryWrapperSelList.eq(BetInfo::getRedpacketId, redPacket.getId());
                List<BetInfo> betInfoList = betInfoMapper.selectList(betInfoLambdaQueryWrapperSelList);
                editMessageCaption = redPacket.getEditMessageCaption(tgUserNapper.selectById(redPacket.getTgUserId()), betInfoList, true);
                new MineClearanceBot().execute(editMessageCaption);
            }
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 解锁前检查当前线程是否持有该锁
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        String amount = "3.14";

        String s = amount.substring(0,amount.length() - 1) + "0";
        System.out.println(s);
    }


    public void processingTransaction(List<BetInfo> betInfoList, RedPacket redPacket) {
        try {
            for (BetInfo info : betInfoList) {
                BigDecimal infoAmount = info.getAmount();
                String toString = infoAmount.stripTrailingZeros().toPlainString();
                int size = toString.length() - 1;
                if (toString.substring(size).equals(redPacket.getMines().toString())) {
                    info.setDarkLightning(0);
                    info.setIsRadar(0);
                } else {
                    info.setDarkLightning(1);
                    info.setIsRadar(1);
                }
                betInfoMapper.updateById(info);
            }
            //排序;
            Config config = RedisUntils.getConfig();
            BigDecimal redPacketAmount = redPacket.getAmount();
            BigDecimal redPacketMulriple = redPacket.getMulriple();
            BigDecimal frozenAmount = redPacketAmount.multiply(redPacketMulriple);
            //0是 1否
            List<BetInfo> isRadarBetInfoList = betInfoList.stream().filter(s -> s.getIsRadar() == 0).collect(Collectors.toList());
            List<BetInfo> noRadarBetInfoList = betInfoList.stream().filter(s -> s.getIsRadar() == 1).collect(Collectors.toList());
            Date date = new Date();
            //没有中雷,给用户解除冻结金额,添加抢到的红包的金额;
            for (BetInfo betInfo : noRadarBetInfoList) {
                String tgUserId = betInfo.getTgUserId();
                TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + tgUserId), TgUser.class);
                BigDecimal balance = tgUser.getBalance();
                BigDecimal amount = betInfo.getAmount();
                //没有中雷;
                Capital capital = new Capital();
                capital.setTgUserId(tgUser.getId());
                capital.setUserName(tgUser.getUserName());
                capital.setFirstName(tgUser.getFirstName());
                capital.setBeforeAmount(balance.setScale(2, RoundingMode.HALF_UP));
                capital.setAmount(amount);
                capital.setRedpacketId(betInfo.getRedpacketId());
                capital.setAfterAmount(tgUser.getBalance().add(amount).setScale(2, RoundingMode.HALF_UP));
                capital.setTime(date);
                capital.setType(2);
                capitalMapper.insert(capital);
                tgUser.setFrozenAmount(tgUser.getFrozenAmount().subtract(frozenAmount));
                tgUser.setBalance(tgUser.getBalance().add(frozenAmount).add(amount));
                tgUserNapper.updateById(tgUser);
                RedisUntils.setValue(Constants.TGUSER + tgUser.getTgId(), JSON.toJSONString(tgUser));
            }
            //中雷了
            for (BetInfo betInfo : isRadarBetInfoList) {
                String tgUserId = betInfo.getTgUserId();
                TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + tgUserId), TgUser.class);
                //删除用户冻结金额;
                tgUser.setFrozenAmount(tgUser.getFrozenAmount().subtract(frozenAmount));
                //添加赔付记录;
                Capital capital = initCapital(tgUser, redPacket, date);
                capital.setAmount(frozenAmount);
                capital.setAfterAmount(tgUser.getBalance().setScale(2, RoundingMode.HALF_UP));
                capital.setType(3);
                capitalMapper.insert(capital);
                tgUserNapper.updateById(tgUser);
                RedisUntils.setValue(Constants.TGUSER + tgUser.getTgId(), JSON.toJSONString(tgUser));
            }
            //发包者添加金额;
            if (isRadarBetInfoList.size() > 0) {
                try {
                    int size = isRadarBetInfoList.size();
                    //盈利金额;
                    BigDecimal amount = frozenAmount.multiply(new BigDecimal(size));
                    redPacket.setZhongleiProfit(amount);
                    //计算佣金;
                    BigDecimal commission = amount.multiply(config.getCommission()).multiply(new BigDecimal("0.01"));
                    //String tgUserId = betInfoList.get(0).getTgUserId();
                    TgUser tgUser = tgUserNapper.selectById(redPacket.getTgUserId());
                    //TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + redPacket.getTgUserId()), TgUser.class);
                    LambdaQueryWrapper<Inviter> inviteLinkLambdaQueryWrapper = new LambdaQueryWrapper<Inviter>();
                    inviteLinkLambdaQueryWrapper.eq(Inviter::getBeInviteTgId, redPacket.getTgUserId());
                    Inviter inviter = inviterMapper.selectOne(inviteLinkLambdaQueryWrapper);
                    BigDecimal rebateCommission = BigDecimal.ZERO;
                    if (inviter != null) {
                        //计算上级抽成;
                        rebateCommission = amount.multiply(config.getRebateCommission()).multiply(new BigDecimal("0.01"));
                    }
                    //佣金金额;
                    redPacket.setCommissionIncome(commission);
                    //上级抽取
                    redPacket.setAgencyIncome(rebateCommission);
                    //实际应得;
                    BigDecimal actualArrival = amount.add(redPacketAmount);

                    redPacket.setActualArrival(actualArrival);
                    redPacketMapper.updateById(redPacket);
                    //修改发包用户金额：
                    tgUser.setBalance(tgUser.getBalance().add(actualArrival));
                    tgUserNapper.updateById(tgUser);
                    RedisUntils.setValue(Constants.TGUSER + tgUser.getTgId(), JSON.toJSONString(tgUser));

                    //佣金抽取记录添加
                    Capital commissionIncome = initCapital(tgUser, redPacket, date);
                    commissionIncome.setAmount(commission);
                    commissionIncome.setType(6);
                    capitalMapper.insert(commissionIncome);

                    //发送红包返利记录添加
                    Capital actualArrivalCapital = initCapital(tgUser, redPacket, date);
                    actualArrivalCapital.setAmount(actualArrival);
                    actualArrivalCapital.setAfterAmount(tgUser.getBalance().setScale(2, RoundingMode.HALF_UP));
                    actualArrivalCapital.setType(1);
                    capitalMapper.insert(actualArrivalCapital);

                    //上级返佣;
                    if (inviter != null) {
                        //代理抽成记录添加;
                        Capital agencyIncomeCapital = initCapital(tgUser, redPacket, date);
                        agencyIncomeCapital.setAmount(rebateCommission);
                        agencyIncomeCapital.setType(7);
                        capitalMapper.insert(agencyIncomeCapital);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }


    public Capital initCapital(TgUser tgUser, RedPacket redPacket, Date date) {
        Capital capital = new Capital();
        capital.setTgUserId(tgUser.getId());
        capital.setUserName(tgUser.getUserName());
        capital.setFirstName(tgUser.getFirstName());
        capital.setBeforeAmount(tgUser.getBalance().setScale(2, RoundingMode.HALF_UP));
        capital.setRedpacketId(redPacket.getId());
        capital.setTime(date);
        return capital;
    }

    public void giveRedEnvelopesTask(TgUser tgUser, RedPacket redPacket, Integer messageIdSend, boolean flag) {
        Config config = RedisUntils.getConfig();
        RLock lock = redissonClient.getLock(redPacketId + tgUser.getId());
        boolean isLocked;
        try {
            isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (isLocked) {
                log.info("获取锁成功======{}", tgUser.getId());
            } else {
                log.info("获取锁失败======{}", tgUser.getId());
            }
            if (tgUser.getBalance().doubleValue() < redPacket.getAmount().doubleValue()) {
                if (messageIdSend == null) {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                    return;
                }
                if (flag) {
                    //说明余额不足;
                    SendMessage sendMessage = SendMessageUntils.initSendMessage(config.getGroupChatId(), "余额不足,当前余额为: " + tgUser.getBalance() + "当前交易中的冻结金额为" + tgUser.getFrozenAmount());
                    sendMessage.setReplyToMessageId(messageIdSend);
                    new MineClearanceBot().sendMessage(sendMessage);
                    return;
                } else {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                    return;
                }

            }
            BigDecimal amount = redPacket.getAmount();
            List<Double> doubleList = NumTest.initAmount(BigDecialUntils.getIntegerNumber(redPacket.getAmount()), redPacket.getRedPacketSum());
            doubleList = doubleList.stream().sorted(Comparator.comparing(Double::doubleValue).reversed()).collect(Collectors.toList());
            redPacket.setDataAmount(JSON.toJSONString(doubleList));
            redPacket.setDataIndex(1);
            redPacketMapper.insert(redPacket);
            //进行第一次抢;
            LambdaQueryWrapper<TgUser> tgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tgUserLambdaQueryWrapper.eq(TgUser::getType, 1);
            List<TgUser> tgUserList = tgUserNapper.selectList(tgUserLambdaQueryWrapper);
            int index = (int) (Math.random() * tgUserList.size());
            TgUser jiaUser = tgUserList.get(index);
            //开始计算红包;
            BetInfo betInfo = new BetInfo();
            betInfo.setTime(new Date());
            betInfo.setFirstName(jiaUser.getFirstName());
            betInfo.setIsRadar(0);
            betInfo.setRedpacketId(redPacket.getId());
            betInfo.setAmount(BigDecimal.valueOf(doubleList.get(0)));
            betInfo.setTgUserId(jiaUser.getTgId());
            betInfo.setDarkLightning(0);
            betInfoMapper.insert(betInfo);
            RedisUntils.setValueTime(Constants.betInfoRedPacket + redPacket.getId(), JSON.toJSONString(betInfo), 1, TimeUnit.DAYS);
            RedisUntils.setValueTime(Constants.repackOpenAutoInfo + redPacket.getId() + jiaUser.getTgId(), jiaUser.getFirstName(), 5, TimeUnit.MINUTES);
            SendPhoto photoMessage = redPacket.getSendPhotoMessage(tgUser);
            Message execute = new MineClearanceBot().execute(photoMessage);
            Long chatId = execute.getChatId();
            Integer messageId = execute.getMessageId();
            redPacket.setMessageId(messageId);
            redPacket.setChatId(chatId.toString());
            redPacketMapper.updateById(redPacket);
            //存储红包详情;
            RedisUntils.setValue(Constants.redPacket + redPacket.getId(), JSON.toJSONString(redPacket));
            //添加变更记录;
            Capital capital = new Capital();
            capital.setTime(new Date());
            capital.setTgUserId(tgUser.getId());
            capital.setUserName(tgUser.getUserName());
            capital.setFirstName(tgUser.getFirstName());
            capital.setAmount(amount);
            capital.setBeforeAmount(tgUser.getBalance().setScale(2, RoundingMode.UP));
            capital.setAfterAmount(tgUser.getBalance().subtract(amount).setScale(2, RoundingMode.UP));
            capital.setType(0);
            capital.setRedpacketId(redPacket.getId());
            capitalMapper.insert(capital);
            BigDecimal balance = tgUser.getBalance();
            tgUser.setBalance(balance.subtract(amount));
            //修改用户账户的金额;
            tgUserNapper.updateById(tgUser);
            RedisUntils.setValue(Constants.TGUSER + tgUser.getTgId(), JSON.toJSONString(tgUser));
            lock.unlock();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
